<template>
  <div class="snow">
    <canvas ref="cvs" :width="rect.width" :height="rect.height"></canvas>
  </div>
</template>

<script lang="ts" setup name="Snow">
import { computed, onMounted, ref } from 'vue'

const cvs = ref<HTMLCanvasElement | null>()
const ctx = computed(
  () => cvs.value?.getContext('2d') as CanvasRenderingContext2D
)
const rect = computed(() => {
  const { clientWidth: width, clientHeight: height } =
    document.documentElement || document.body
  return {
    width,
    height,
  }
})
const rectList = Array.from(new Array(400)).map(() => ({
  x: Math.random() * rect.value.width,
  y: Math.random() * rect.value.height,
  step: Math.random() * 2.5 + 0.5,
}))

const render = () => {
  ctx.value.fillStyle = '#ffffff'
  ctx.value.clearRect(0, 0, rect.value.width, rect.value.height)

  ctx.value.beginPath()
  rectList.forEach((v) => {
    v.y = v.y > rect.value.height ? 0 : (v.y += v.step)
    ctx.value.rect(v.x, v.y, 3, 3)
  })
  ctx.value.fill()
  window.requestAnimationFrame(render)
}

onMounted(() => {
  render()
})
</script>

<style lang="scss" scoped>
.snow {
  canvas {
    background-color: #000;
  }
}
</style>
